import os
import sys

from PySide6.QtCore import QTimer, Slot, QPropertyAnimation, QPoint, QProcess
from PySide6.QtGui import QGuiApplication, QCloseEvent, QShowEvent, QMouseEvent

from CoreWidget import ContentWidget,MenuBar
from appInit import initNotice
from noticeWidget import *

from core.setting import WINDOWTITLE
from core.unzip import unzipFile
from core.get_url import isSteamUrl

class MyWindow(QWidget):
    initObject = None
    scaleOutMoveSignal = Signal(bool)

    def __init__(self,parent=None):
        super().__init__(parent)
        self._isChangeState = False
        self._inLeft = False
        self._inRight = False

        self.topMenu = MenuBar()
        self.contentWidget = ContentWidget()
        self.previewPageWidget = None
        self.setShortcutWindow = setShortcut()
        self.historyWindow = historysPage()
        self.appSetWindow = appSetupPage()
        self.shareWindow = sharePage()

        self.initSetUp()
        self.bind()

        self.screenWidth,self.screenHeight = self.getWindowScreen()
        self.windowWidth,self.windowHeight = self.geometry().size().toTuple()

    def bind(self):
        self.scaleOutMoveSignal.connect(self.scaleOutMove)

        # 连接顶部菜单条功能按钮信号
        self.topMenu.bar.close.signalObject.closeWindow.connect(self.closeWindow)
        self.topMenu.bar.minning.signalObject.minWindow.connect(self.minWindow)

        # 连接其他子窗口
        self.contentWidget.mainPage.linkBar.changeCell.connect(self.setShortcutWindowShow)
        self.topMenu.bar.historyIcon.clicked.connect(self.historyWindowShow)
        self.topMenu.bar.setIcon.clicked.connect(self.appSetWindowShow)
        self.topMenu.bar.shareIcon.clicked.connect(self.shareWindowShow)
        self.setShortcutWindow.setShortcutCell.connect(self.contentWidget.mainPage.linkBar.setCell)

        self.historyWindow.jumpUrl.connect(lambda url:self.contentWidget.mainPage.urlEdit.setText(url))
        self.appSetWindow.restart.connect(self.restartEvent)

    @Slot(str,str)
    def setShortcutWindowShow(self,url:str,text:str):
        self.setShortcutWindow.setInput(text,url)
        self.setShortcutWindow.show()

    def historyWindowShow(self):
        x = self.frameGeometry().topRight().x() + 5
        y = (self.windowHeight - self.historyWindow._height) // 2 + self.frameGeometry().y()
        self.historyWindow.move(x,y)
        self.historyWindow.updateHistory()
        self.historyWindow.show()

    def appSetWindowShow(self):
        self.appSetWindow.show()

    def shareWindowShow(self):
        x = self.frameGeometry().topLeft().x() - self.shareWindow._width - 5
        y = (self.windowHeight - self.shareWindow._height) // 2 + self.frameGeometry().y()
        self.shareWindow.move(x,y)
        self.shareWindow.show()

    def initSetUp(self):
        self.setWindowTitle(WINDOWTITLE)
        self.setWindowIcon(QPixmap('./img/terminal2.png'))
        self.setWindowFlags(Qt.WindowType.Window | Qt.WindowType.FramelessWindowHint) # 设置无边框
        self.setAttribute(Qt.WA_TranslucentBackground) # 设置透明
        self.setMouseTracking(True)
        self.setCursor(QPixmap('./img/mouse.png'))

        self.setMaximumSize(650,400)
        self.setMinimumSize(50,50)
        self.resize(650, 400)

        self.setObjectName('MainQWidget')
        self.setStyleSheet('''
                                #ContentWidget{
                                    background-color: #21252b;
                                    border-bottom-left-radius: 45px;
                                    border-bottom-right-radius: 45px;
                                }
                                #topMenu{
                                    background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                    stop: 0.7 #383e49, stop: 0.8 #30363f, stop: 0.9 #282d35, stop: 1.0 #21252b);
                                    border-top-left-radius: 10px;
                                    border-top-right-radius: 10px;
                                }
                                QLineEdit{
                                    color: white;
                                    padding-left: 12px;
                                    padding-right: 40px;
                                    border: 2px solid gray;
                                    border-radius: 20px;
                                    background-color: #282c35;
                                }
                                QTableWidget{
                                    margin:1px;
                                    background:#21242d;
                                    border-radius: 40px;
                                    outline:none;
                                }
                                QTableWidget::item{
                                    border-radius: 40px;
                                }
                                QPushButton{
                                    background:rgba(0,0,0,0);
                                }
                                #initNotice,#NoticeBase{
                                    background-color: #1a1c1e;
                                    border-radius: 20px;
                                }
                                #NoticeBase>QPushButton{
                                    color:#ffffff;
                                    background-color:#1b6ef3ff;
                                    border-radius:16px;
                                }
                                #NoticeBase>QPushButton:hover{
                                    color:#ffffff;
                                    background-color:#a8c7faff;
                                }
                                #initNotice>QLabel,#NoticeBase>QLabel{
                                    color:white;
                                }
                                QToolTip{
                                    border: 0px solid black;
                                    border-radius: 3px;
                                    background:#21252b;
                                    color:white;
                                }
                            ''')

    def showUi(self):
        mainLayout = QVBoxLayout(self)

        # 二次封装实现控件遮挡移动
        contentWidget = QWidget()
        self.contentWidget.setParent(contentWidget)

        mainLayout.addWidget(self.topMenu)
        mainLayout.addWidget(contentWidget)

        mainLayout.setContentsMargins(0, 0, 0, 0)
        mainLayout.setSpacing(0)

    def setHintWindow(self,bl):
        if bl:
            old_flags = self.windowFlags()
            self.windowHandle().setFlags(old_flags | Qt.WindowType.WindowStaysOnTopHint)
        else:
            self.windowHandle().setFlags(Qt.WindowType.Window | Qt.WindowType.FramelessWindowHint)

    def init(self,isCmdInit:bool=False):
        @Slot(bool)
        def closeNoticeWindow(bl):
            notice.close()
            self.showUi()
            if not bl:
                self.close()

        notice = initNotice(parent=self)
        notice.closeSignal.closeNotice.connect(closeNoticeWindow)

        pos = self.geometry().size() - notice.geometry().size()
        notice.move(pos.width()//2,pos.height()//2) # 相对应主窗口移动
        notice.show()

        if isCmdInit:
            unzipFile()
            notice.startinit()
        else:
            notice.startWorkshopDirinit()


    def getWindowScreen(self):
        windowScreen = QGuiApplication.primaryScreen().size()
        return windowScreen.width(),windowScreen.height()

    @Slot(bool)
    def scaleWindow(self,bl):
        if bl:
            self.resize(self.minimumSize())
        else:
            self.resize(self.maximumSize())

    @Slot(bool)
    def scaleOutMove(self,bl):
        if bl:
            move = QPropertyAnimation(self, b'pos', parent=self)
            move.setStartValue(QPoint(-self.topMenu.icon.width(), self.pos().y()))
            move.setEndValue(QPoint(0, self.pos().y()))
            move.start()
        else:
            move = QPropertyAnimation(self, b'pos', parent=self)
            move.setEndValue(QPoint(self.screenWidth - self.topMenu.icon.width(), self.pos().y()))
            move.start()
        move.finished.connect(lambda:self.scaleWindow(True))

    def windowMoveAnimation(self,s):
        move = QPropertyAnimation(self,b'pos',parent=self)
        move.setDuration(s)
        move.setEndValue(QPoint(self.screenWidth-self.windowWidth,self.geometry().y()))
        move.start()

    def topRevertStyle(self):
        self.topMenu.icon.setStyleSheet('background-color:none;border-radius:none')
        self.topMenu.bar.setStyleSheet('background-color:none;border-radius:none')
        self.topMenu.setStyleSheet('background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0.7 #383e49, stop: 0.8 #30363f, stop: 0.9 #282d35, stop: 1.0 #21252b);'
                                    'border-top-left-radius: 10px;'
                                    'border-top-right-radius: 10px;')

    def restartEvent(self):
        QApplication.closeAllWindows()
        # print(QApplication.applicationFilePath(),os.path.normpath(sys.argv[0]))
        pythonExePath = os.path.normpath(sys.executable)
        mainPath = os.path.normpath(sys.argv[0])
        QProcess.startDetached(pythonExePath,[mainPath])

    def closeWindow(self):
        self.close()

    def minWindow(self):
        x = self.geometry().topLeft().x() + self.windowWidth // 2
        if x <= self.screenWidth // 2:
            self._inLeft = True
            self.inLeftMoveEvent()
        else:
            self._inRight = True
            self.inRightMoveEvent()

    def inLeftMoveEvent(self):
        if not self._isChangeState:
            self.setHintWindow(True)
            self.contentWidget.moveSignal.topMove.emit(True)

            self.topMenu.icon.setStyleSheet('background-color:#383e49')
            self.topMenu.bar.setStyleSheet('background-color:#383e49')
            self.topMenu.setStyleSheet('border-radius:20px;background-color:rgba(0,0,0,0)')

            self.topMenu.moveSignal.leftMove.emit(True)
            self.scaleOutMoveSignal.emit(True)

            self.topMenu.setStyleSheet('border-radius:0;background-color:rgba(0,0,0,0)')
            self.topMenu.icon.setStyleSheet('background-color:#383e49;'
                                            'border-top-right-radius:20px;'
                                            'border-bottom-right-radius:20px;')
            self._isChangeState = True

        else:
            self.scaleOutMoveSignal.emit(True)
            self.topMenu.icon.setStyleSheet('background-color:#383e49;'
                                            'border-top-right-radius:20px;'
                                            'border-bottom-right-radius:20px;')

    def inRightMoveEvent(self):
        if not self._isChangeState:
            self.setHintWindow(True)
            self.contentWidget.moveSignal.topMove.emit(True)

            self.topMenu.icon.setStyleSheet('background-color:#383e49')
            self.topMenu.bar.setStyleSheet('background-color:#383e49')
            self.topMenu.setStyleSheet('border-radius:20px;background-color:rgba(0,0,0,0)')

            self.topMenu.moveSignal.leftMove.emit(True)
            self.scaleOutMoveSignal.emit(False)

            self.topMenu.setStyleSheet('border-radius:0;background-color:rgba(0,0,0,0)')
            self.topMenu.icon.setStyleSheet('background-color:#383e49;'
                                            'border-top-left-radius:20px;'
                                            'border-bottom-left-radius:20px;')
            self._isChangeState = True
        else:
            self.scaleOutMoveSignal.emit(False)
            self.topMenu.icon.setStyleSheet('background-color:#383e49;'
                                            'border-top-left-radius:20px;'
                                            'border-bottom-left-radius:20px;')

    def mouseMoveEvent(self, event: QMouseEvent) -> None:
        super().mouseMoveEvent(event)

        topLeftPos = self.geometry().topLeft()
        bottomRightPos = self.geometry().bottomRight()

        if topLeftPos.x() <= 50:
            self._inLeft = True
        elif bottomRightPos.x() >= self.screenWidth - 50:
            self._inRight = True
        else:
            self._inLeft = False
            self._inRight = False
            if self._isChangeState:
                self.topMenu.icon.setStyleSheet('background-color:#383e49;'
                                                'border-radius:20px;')

    def enterEvent(self, event):
        super().enterEvent(event)

        clipText = QApplication.clipboard().text().strip()
        if (isSteamUrl(clipText) and
                clipText != self.contentWidget.mainPage.urlEdit.text()):
            self.contentWidget.mainPage.urlEdit.setText(clipText)

    def leaveEvent(self, event):
        super().leaveEvent(event)

        if self._inLeft:
            self.inLeftMoveEvent()

        elif self._inRight:
            self.inRightMoveEvent()

        elif self._isChangeState and not self._inLeft and not self._inRight:
            self.resize(self.windowWidth,self.windowHeight)
            self.setHintWindow(False)

            self.topMenu.bar.setStyleSheet('background-color:#383e49')
            self.topMenu.moveSignal.leftMove.emit(False)

            QTimer.singleShot(200,self.topRevertStyle)

            if self.geometry().topRight().x() > self.screenWidth:
                QTimer.singleShot(150,lambda :self.windowMoveAnimation(100))

            self.contentWidget.moveSignal.topMove.emit(False)

            self._isChangeState = False

    def paintEvent(self, event):
        opt = QStyleOption()
        opt.initFrom(self)
        p = QPainter(self)
        self.style().drawPrimitive(QStyle.PrimitiveElement.PE_Widget,opt,p,self)

        super().paintEvent(event)

    def showEvent(self, event:QShowEvent) -> None:
        super().showEvent(event)

        if not os.path.exists(BASEPATH + os.path.normpath('/steamcmd/steamapps/workshop')):
            os.makedirs(BASEPATH + os.path.normpath('/steamcmd/steamapps/workshop'))

        with open('../log/initLog','r',encoding='utf-8') as data:
            firstLine = data.readline().strip().split(':')
            if 'True' not in firstLine:
                self.init(isCmdInit=True)
            elif len(os.listdir(BASEPATH + os.path.normpath('/steamcmd/steamapps/workshop'))) > 0:
                self.init()
            else:
                self.showUi()

    def closeEvent(self, event: QCloseEvent) -> None:

        # 删除imgCache的所有临时照片
        # if len(os.listdir('./imgCache')) != 0:
        #     for childFile in os.listdir('./imgCache'):
        #         os.remove(os.path.join('./imgCache',childFile))

        super().closeEvent(event)


if __name__ == "__main__":
    app = QApplication()
    window = MyWindow()
    window.show()
    app.exec()
